const path = require('path')
const webpack = require('webpack')
const { merge } = require('webpack-merge')
const WebpackDevServer = require('webpack-dev-server')
const defaultConfig = require('../template/webpack/webpack.config.default')

module.exports = async (args) => {
  // 读取用户配置文件
  const userConfig = require(path.join(process.cwd(), 'vue3.config')) || {}

  // 组装 webpack 配置对象（将默认配置和命令相关联配置合并）
  const config = merge(defaultConfig, {
    mode: 'development'
  })

  // 创建 webpack 编译器实例
  const compiler = webpack(config)

  // 创建 dev server 实例
  const server = new WebpackDevServer({
    static: {
      directory: path.join(process.cwd(), 'dist')
    },
    
    // 从命令行参数获取服务器端口
    port: args.port,
    
    // 从配置文件 vue3.config.js 中获取其他配置信息
    ...userConfig.devServer
  }, compiler)

  // 启动 dev server
  await server.start()
}